// 直播服务
// 处理直播流、直播间管理等功能

// 模拟API延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 直播服务
export const liveService = {
  // 获取热门直播间
  async getHotLiveRooms(page = 1, limit = 20) {
    try {
      await delay(300)
      
      // 模拟直播间数据
      const liveRooms = this.generateMockLiveRooms(100)
      
      // 按人气排序
      liveRooms.sort((a, b) => b.viewers - a.viewers)
      
      // 分页处理
      const start = (page - 1) * limit
      const end = start + limit
      
      return {
        rooms: liveRooms.slice(start, end),
        total: liveRooms.length,
        page,
        limit,
        totalPages: Math.ceil(liveRooms.length / limit)
      }
    } catch (error) {
      console.error('获取热门直播间失败:', error)
      throw error
    }
  },
  
  // 获取分类直播间
  async getLiveRoomsByCategory(category, page = 1, limit = 20) {
    try {
      await delay(300)
      
      // 模拟直播间数据
      let liveRooms = this.generateMockLiveRooms(100)
      
      // 按分类过滤
      if (category && category !== '全部') {
        liveRooms = liveRooms.filter(room => room.category === category)
      }
      
      // 按人气排序
      liveRooms.sort((a, b) => b.viewers - a.viewers)
      
      // 分页处理
      const start = (page - 1) * limit
      const end = start + limit
      
      return {
        rooms: liveRooms.slice(start, end),
        total: liveRooms.length,
        page,
        limit,
        totalPages: Math.ceil(liveRooms.length / limit)
      }
    } catch (error) {
      console.error(`获取${category}分类直播间失败:`, error)
      throw error
    }
  },
  
  // 获取直播间详情
  async getLiveRoomDetail(roomId) {
    try {
      await delay(200)
      
      // 生成模拟直播间详情
      const room = this.generateMockLiveRooms(1)[0]
      room.id = roomId
      
      // 添加更多详情信息
      room.description = '这是一个精彩的直播内容，欢迎大家前来观看和互动！'
      room.tags = this.getRandomTags()
      room.stats = {
        peakViewers: Math.floor(room.viewers * 1.2),
        totalViews: room.viewers * 10,
        avgWatchTime: Math.floor(Math.random() * 30) + 10,
        followerConversion: (Math.random() * 5).toFixed(2)
      }
      room.startTime = new Date(Date.now() - Math.random() * 3600000 * 2).toISOString()
      room.isVerified = Math.random() > 0.3
      room.isOfficial = Math.random() > 0.8
      
      // 添加推荐直播间
      room.recommendedRooms = this.generateMockLiveRooms(6)
      
      return room
    } catch (error) {
      console.error(`获取直播间${roomId}详情失败:`, error)
      throw error
    }
  },
  
  // 获取直播间流地址
  async getLiveStreamUrl(roomId, quality = '720p') {
    try {
      await delay(100)
      
      // 模拟返回流地址
      return {
        url: `https://example.com/live/${roomId}/stream.m3u8?quality=${quality}`,
        hls: true,
        quality,
        availableQualities: ['360p', '480p', '720p', '1080p', '4K'],
        streamType: 'hls'
      }
    } catch (error) {
      console.error(`获取直播流失败:`, error)
      throw error
    }
  },
  
  // 获取直播弹幕
  async getLiveDanmakus(roomId) {
    try {
      await delay(100)
      
      // 模拟返回弹幕数据
      const danmakus = []
      const count = Math.floor(Math.random() * 20) + 10
      
      for (let i = 0; i < count; i++) {
        danmakus.push({
          id: `danmaku_${Date.now()}_${i}`,
          roomId,
          userId: `user_${Math.floor(Math.random() * 1000)}`,
          userName: `用户${Math.floor(Math.random() * 1000)}`,
          content: this.getRandomDanmakuContent(),
          color: this.getRandomColor(),
          type: ['normal', 'gift', 'welcome', 'system'][Math.floor(Math.random() * 4)],
          timestamp: Date.now(),
          avatar: `https://placehold.co/32x32/667eea/FFFFFF?text=U`
        })
      }
      
      return danmakus
    } catch (error) {
      console.error('获取直播弹幕失败:', error)
      throw error
    }
  },
  
  // 发送直播弹幕
  async sendLiveDanmaku(roomId, content, userId, userName, color = '#FFFFFF') {
    try {
      await delay(50)
      
      const danmaku = {
        id: `danmaku_${Date.now()}`,
        roomId,
        userId,
        userName,
        content,
        color,
        type: 'normal',
        timestamp: Date.now(),
        avatar: `https://placehold.co/32x32/667eea/FFFFFF?text=U`
      }
      
      // 在实际项目中，这里应该调用API发送弹幕
      // const response = await fetch('/api/live/danmakus', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(danmaku)
      // })
      // return await response.json()
      
      return danmaku
    } catch (error) {
      console.error('发送直播弹幕失败:', error)
      throw error
    }
  },
  
  // 获取直播分类
  async getLiveCategories() {
    try {
      await delay(100)
      
      return [
        { id: 'all', name: '全部', icon: '🎬' },
        { id: 'game', name: '游戏', icon: '🎮' },
        { id: 'music', name: '音乐', icon: '🎵' },
        { id: 'chat', name: '聊天', icon: '💬' },
        { id: 'tech', name: '科技', icon: '💻' },
        { id: 'food', name: '美食', icon: '🍔' },
        { id: 'sports', name: '体育', icon: '⚽' },
        { id: 'anime', name: '动漫', icon: '🎭' },
        { id: 'outdoor', name: '户外', icon: '🏕️' },
        { id: 'art', name: '艺术', icon: '🎨' }
      ]
    } catch (error) {
      console.error('获取直播分类失败:', error)
      return []
    }
  },
  
  // 生成模拟直播间数据
  generateMockLiveRooms(count) {
    const categories = ['游戏', '音乐', '聊天', '科技', '美食', '体育', '动漫', '户外', '艺术']
    const statuses = ['live', 'live', 'live', 'live', 'live', 'live', 'live', 'live', 'live', 'ended']
    
    return Array.from({ length: count }, (_, index) => ({
      id: `live_${Date.now()}_${index}`,
      title: `${this.getRandomTitle()} - 直播进行中`,
      cover: `https://placehold.co/400x225/00a1d6/FFFFFF?text=Live+${index + 1}`,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      viewers: Math.floor(Math.random() * 100000) + 100,
      category: categories[Math.floor(Math.random() * categories.length)],
      streamer: {
        id: `streamer_${Math.floor(Math.random() * 100)}`,
        name: `主播${Math.floor(Math.random() * 100)}`,
        avatar: `https://placehold.co/50x50/667eea/FFFFFF?text=S`,
        followers: Math.floor(Math.random() * 100000) + 1000
      },
      tags: this.getRandomTags(),
      isHot: Math.random() > 0.8,
      isRecommended: Math.random() > 0.9
    }))
  },
  
  // 获取随机标签
  getRandomTags() {
    const allTags = ['热门', '新主播', '专业', '搞笑', '互动', '教学', '实况', '挑战', '颜值', '才艺']
    const tagCount = Math.floor(Math.random() * 3) + 1
    const tags = []
    
    for (let i = 0; i < tagCount; i++) {
      const tag = allTags[Math.floor(Math.random() * allTags.length)]
      if (!tags.includes(tag)) {
        tags.push(tag)
      }
    }
    
    return tags
  },
  
  // 获取随机标题
  getRandomTitle() {
    const titles = [
      '精彩直播',
      '新人首播',
      '技术教学',
      '游戏实况',
      '聊天互动',
      '才艺展示',
      '美食制作',
      '户外探险',
      '音乐分享',
      '挑战赛'
    ]
    return titles[Math.floor(Math.random() * titles.length)]
  },
  
  // 获取随机弹幕内容
  getRandomDanmakuContent() {
    const contents = [
      '666666',
      '主播加油！',
      '刚来，主播在干嘛？',
      '太精彩了！',
      '关注了',
      '送你小花花',
      '哈哈哈',
      '学到了',
      '路过',
      '打卡',
      '主播好棒！',
      '666',
      '前排',
      '沙发',
      '为主播打call'
    ]
    return contents[Math.floor(Math.random() * contents.length)]
  },
  
  // 获取随机颜色
  getRandomColor() {
    const colors = ['#FFFFFF', '#FFFF00', '#FF0000', '#00FF00', '#00FFFF', '#FF00FF']
    return colors[Math.floor(Math.random() * colors.length)]
  }
}

// 导出默认服务
export default liveService